<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <link th:href="@{/assets/grid/css/flexigrid.css}" rel="stylesheet"/>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <title th:text="#{file.manager.title}">文件管理</title>
    <script th:inline="javascript">
        const FILE_TYPE_FILE =0
        const FILE_TYPE_FOLDER =1
        var _gridWidth;
        var _gridHeight;

        function resizePageSize(){
            _gridWidth = $(document).width() - 12;
            _gridHeight = $(document).height() - 65 - 40;
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth - 150) /4;

            // 初始化文件列表表格
            $("#flexigrid-id").flexigrid({
                width: _gridWidth,
                height: _gridHeight,
                url: /*[[@{/file/queryFileInfoListByPage}]]*/ "/file/fileAll",
                dataType: 'json',
                colModel: [
                    {display : 'fileUuid',name : 'fileUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{file.name}]]*/"",name : 'fileName',width : _columnWidth, sortable : true,align : 'center',
                        process:function (v, _trid, _row) {
                            var html =`<div style="display: flex;width: 100px;">`
                            if(_row.fileType ===FILE_TYPE_FOLDER){
                                html +=`<a href="#" style="color: #00b1ef" class="btn "><i class="glyphicon glyphicon-file" style="margin-right:5px "></i><span>${v}</span><a>`
                            }else {
                                html +=`<a href="#" style="color: #f7ba2a" class="btn "onclick="enterDir('${_row.fileUuid}')"><i class="glyphicon glyphicon-folder-close" style="margin-right:5px "></i><span>${v}</span><a>`
                            }

                            html +=`</div>`
                            return html
                        }
                    },
                    {display : /*[[#{file.size}]]*/"",name : 'fileCapacity',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{file.last.time}]]*/"",name : 'modtime',width : _columnWidth, sortable : true,align : 'center'},

                    {display: /*[[#{common.operation}]]*/"操作", name: 'fileUuid', width: _columnWidth, sortable: true, align: 'center',
                        process: function(v, _trid, _row) {
                            var html = '<div>';
                            html += `<a href="#" class="btn btn-primary" onclick="renameFile('${v}', '${_row.fileName}')" title="[[#{file.rename}]]"><i class="glyphicon glyphicon-edit"></i></a>&nbsp;`;
                            var url=/*[[@{/file/downFile}]]*/'';
                            url += "/" + v;
                            html += `<a href=${url} class="btn"  title=[[#{file.download.btn}]] target="_blank"><i class="glyphicon glyphicon-download"></i></a>`;
                            
                            // 为音频/视频文件添加播放按钮
                            const ext = _row.fileName.split('.').pop().toLowerCase();
                            const isMedia = ['mp3','wav','ogg','mp4','webm'].includes(ext);
                            if(isMedia) {
                                html += `<a href="#" class="btn btn-success" onclick="playFile('${v}','${_row.fileName}')" title="[[#{file.play}]]"><i class="glyphicon glyphicon-play"></i></a>&nbsp;`;
                            }
                            
                            if (/*[[${#authorization.expression("hasRole('ROLE_cldk_file_del')")}]]*/ false) {
                                html += `<a href="#" class="btn btn-danger" onclick="deleteFileToRecycle('${v}', '${_row.fileName}')" title="[[#{file.delete.to.recycle}]]"><i class="glyphicon glyphicon-trash"></i></a>&nbsp;`;
                            }
                            html += `<a href="#" class="btn" onclick="shareFileInfo('${v}','${_row.fileName}')" title=[[#{file.share.btn}]]><i class="glyphicon   glyphicon-share"></i></a>`
                            // 注释掉分享按钮
                            // html += `<a href="#" class="btn btn-info" onclick="openShareDialog('${v}')" title="[[#{file.share}]]"><i class="glyphicon glyphicon-share"></i></a>`;
                            html += `</div>`;
                            return html;
                        }
                    }
                ],

                resizable: false,
                useRp: true,
                usepager: true,
                autoload: false,
                hideOnSubmit: true,
                showcheckbox: true,
                rowbinddata: true
            });

            query()

            //文件上传对话框
            $("#upload-file-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.upload.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("#upload-file-name-id").checkDom();
                            if (!flag) {
                                return;
                            }
                            $("#upload-file-form-id").submit();
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            })
            $("#upload-file-form-id").ajaxForm({
                dataType: "json",
                success: function(data) {
                    query();
                    $("#upload-file-dialog-id").dialog('close')
                },
                error: function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })
            //分享初始化
            $("#share-file-dialog-id").dialog({
                autoOpen : false,
                width : 800,
                modal : true,
                resizable : false,
                title: /*[[#{file.share.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })

            // 初始化上传成功提示对话框
            $("#upload-success-dialog").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                title: /*[[#{file.upload.success}]]*/'操作成功',
                buttons: [{
                    text: /*[[#{common.confirm}]]*/'确认',
                    click: function() {
                        $(this).dialog("close");
                    }
                }],
                close: function() {
                    $("#flexigrid-id").flexReload(); // 关闭对话框时刷新列表
                }
            });

            // 初始化权限修改对话框
            $("#modify-permission-dialog-id").dialog({
                autoOpen: false,
                width: 500,
                modal: true,
                resizable: false,
                title: /*[[#{file.modify.permission.dialog}]]*/'修改权限',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'确认',
                        click: function () {
                            saveFilePermission();
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'取消',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });

            // 初始化删除到回收站对话框
            $("#delete-to-recycle-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.delete.to.recycle}]]*/'删除到回收站',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'确认',
                        click: function () {
                            confirmDeleteToRecycle();
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'取消',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]

            });

            // 注释掉分享文件对话框初始化
            // $("#share-file-dialog-id").dialog({
            //     autoOpen: false,
            //     width: 500,
            //     modal: true,
            //     resizable: false,
            //     title: /*[[#{share.title}]]*/'分享文件',
            //     buttons: [
            //         {
            //             text: /*[[#{common.confirm}]]*/'确认',
            //             click: function() {
            //                 var fileId = $(this).attr('fileId'); // 获取文件ID
            //                 var validityPeriod = $("#share-validity-period").val(); // 获取有效期选择
            //                 var customTime = $("#share-custom-time").val(); // 获取自定义时间
            //
            //                 // 计算过期时间
            //                 var expireTime = '';
            //                 if (validityPeriod === 'custom') {
            //                     if (!customTime) {
            //                         message(/*[[#{share.validity.custom.time.required}]]*/'请选择自定义时间');
            //                         return;
            //                     }
            //                     expireTime = customTime;
            //                 } else {
            //                     // 根据选择计算过期时间
            //                     var now = new Date();
            //                     switch(validityPeriod) {
            //                         case '1d':
            //                             now.setDate(now.getDate() + 1);
            //                             break;
            //                         case '3d':
            //                             now.setDate(now.getDate() + 3);
            //                             break;
            //                         case '1w':
            //                             now.setDate(now.getDate() + 7);
            //                             break;
            //                         case '2w':
            //                             now.setDate(now.getDate() + 14);
            //                             break;
            //                         case '1m':
            //                             now.setMonth(now.getMonth() + 1);
            //                             break;
            //                         case '6m':
            //                             now.setMonth(now.getMonth() + 6);
            //                             break;
            //                         case '1y':
            //                             now.setFullYear(now.getFullYear() + 1);
            //                             break;
            //                     }
            //                     expireTime = now.toISOString().slice(0, 16);
            //                 }
            //
            //                 // 注释掉用户选择相关代码
            //                 /*
            //                 // 获取选中的用户
            //                 var treeObj = $.fn.zTree.getZTreeObj("share-user-ztree-id");
            //                 var nodes = treeObj.getCheckedNodes(true);
            //
            //                 if (nodes.length === 0) {
            //                     message('请选择被分享人员');
            //                     return;
            //                 }
            //
            //                 var userIds = [];
            //                 $(nodes).each(function (index, item) {
            //                     userIds.push(item.id);
            //                 });
            //                 */
            //
            //                 // 调用分享接口 - 修改为不需要用户ID
            //                 $.post(/*[[@{/disk/file/doShare}]]*/'', {
            //                     fileId: fileId,
            //                     expireTime: expireTime,
            //                     userIds: '' // 空字符串，表示不需要指定用户
            //                 }, function(data) {
            //                     message(data.msg);
            //                     if (data.success) {
            //                         $("#share-file-dialog-id").dialog('close');
            //                         // 刷新文件列表
            //                         $("#flexigrid-id").flexReload();
            //                     }
            //                 });
            //             }
            //         },
            //         {
            //             text: /*[[#{common.cancel}]]*/'取消',
            //             click: function() {
            //                 $(this).dialog("close");
            //             }
            //         }
            //     ]
            // });

            // 绑定上传按钮点击事件
            $("#upload-file-btn").click(function() {
                $("#upload-dialog").dialog("open");
            });

            // 绑定有效期选择事件
            // $(document).on('change', '#share-validity-period', function() {
            //     var selectedValue = $(this).val();
            //     if (selectedValue === 'custom') {
            //         $("#custom-time-group").show();
            //     } else {
            //         $("#custom-time-group").hide();
            //     }
            // });


            // 初始化重命名对话框
            $("#rename-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                title: /*[[#{file.rename.dialog.title}]]*/'重命名文件',
                buttons: [{
                    text: /*[[#{common.confirm}]]*/'确认',
                    click: function() {
                        confirmRename();
                    }
                }, {
                    text: /*[[#{common.cancel}]]*/'取消',
                    click: function() {
                        $(this).dialog("close");
                    }
                }]
            });

            // 初始化文件冲突处理对话框
            $("#conflict-dialog-id").dialog({
                autoOpen: false,
                width: 500,
                modal: true,
                resizable: false,
                title: '文件冲突处理',
                closeOnEscape: false,
                open: function(event, ui) {
                    $(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
                }
            });

        });//end ready function
            // 注释掉有效期选择事件绑定
            // $(document).on('change', '#share-validity-period', function() {
            //     var selectedValue = $(this).val();
            //     if (selectedValue === 'custom') {
            //         $("#custom-time-group").show();
            //     } else {
            //         $("#custom-time-group").hide();
            //     }
            // });


        // 注释掉打开分享对话框函数
        // function openShareDialog(fileId) {
        //     // 重置对话框参数
        //     $("#share-validity-period").val('1d');
        //     $("#share-custom-time").val('');
        //     $("#custom-time-group").hide();
        //
        //     // 存储文件ID到对话框属性
        //     $("#share-file-dialog-id").attr('fileId', fileId);
        //
        //     // 注释掉用户树初始化代码 - 不再需要用户选择功能
        //     // 初始化用户树的代码已被注释掉
        //
        //     // 打开对话框
        //     $("#share-file-dialog-id").dialog('open');
        // }

        // 同步文件数据
        function syncFileData() {
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/syncFileData}]]*/'',
                data: [],
                success: function (data) {
                    message(data.msg);
                    if(data.success) {
                        $("#flexigrid-id").flexReload();
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        // 文件上传
        function uploadFile() {
            $("#upload-file-parent-id").val($("#file-folder-id").attr("parent-id"));
            $("#upload-file-dialog-id").dialog('open')

        }

        // 保存文件权限设置
        function saveFilePermission() {
            let fileId = $("#current-file-id").val();
            let permissionType = $("#permission-type-select").val();
            let treeObj = $.fn.zTree.getZTreeObj("user-permission-ztree-id");
            let nodes = treeObj.getCheckedNodes(true);

            if (nodes.length === 0) {
                message(/*[[#{file.permission.no.user.selected}]]*/'请选择用户');
                return;
            }

            let userIds = [];
            $(nodes).each(function (index, item) {
                userIds.push(item.id);
            });

            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/saveFilePermission}]]*/'',
                data: [
                    {name: "fileId", value: fileId},
                    {name: "userIds", value: userIds},
                    {name: "permissionType", value: permissionType}
                ],
                success: function (data) {
                    message(data.msg);
                    if (data.success) {
                        $("#modify-permission-dialog-id").dialog('close');
                        $("#flexigrid-id").flexReload();
                    }
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        // 权限设置的zTree配置
        var permissionSetting = {
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onLoadSuccess: function(treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("user-permission-ztree-id");
                }
            }
        };

        // 打开权限修改对话框
        function modifyFilePermission(fileId) {
            $("#current-file-id").val(fileId);
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryUserListForPermission}]]*/'',
                data: [{name: "fileId", value: fileId}],
                success: function (data) {
                    $.fn.zTree.init($('#user-permission-ztree-id'), permissionSetting, data);
                    $("#modify-permission-dialog-id").dialog('open');
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        // 确认删除到回收站
        function confirmDeleteToRecycle() {
            let fileIds = $("#delete-file-id").val();
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/deleteToRecycle}]]*/'',
                data: [{name: "fileIds", value: fileIds}],
                success: function (data) {
                    message(data.msg);
                    if (data.success) {
                        $("#delete-to-recycle-dialog-id").dialog('close');
                        $("#flexigrid-id").flexReload();
                    }
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        /**
         * 表格查询
         */
        function query() {
            var parentId = $("#file-folder-id").attr("parent-id");
            var fileName = $("#file-name-id").val();

            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"parentId",value:parentId},
                    {name:"fileName",value:fileName}
                ]
            }).flexReload()
        }
        /**
         *进入文件夹
         */
        function enterDir(fileUuid) {
            $("#file-folder-id").attr("parent-id",fileUuid)
            query()
        }
        /**
         *进入上一级文件夹
         */
        function upDir() {
            var fileUuid = $("#file-folder-id").attr("parent-id");
            $.ajax({
                type:'post',
                async:false,
                dataType:'json',
                url:/*[[@{/file/queryFileInfoById}]]*/'',
                data:[
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if (data){
                        enterDir(data['parentUuid'])
                    }
                },
                error:function (msg) {
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }


        // 删除文件到回收站
        function deleteFileToRecycle(fileId, fileName) {
            $("#delete-file-id").val(fileId);
            $("#delete-file-name").text(fileName);
            $("#delete-to-recycle-dialog-id").dialog('open');
        }

        // 重命名文件
        function renameFile(fileId, fileName) {
            $("#rename-file-id").val(fileId);
            $("#new-file-name").val(fileName);
            $("#rename-dialog-id").dialog('open');
        }

        // 确认重命名
        function confirmRename() {
            var fileId = $("#rename-file-id").val();
            var newName = $("#new-file-name").val();

            if (!newName) {
                message(/*[[#{file.rename.empty}]]*/'文件名不能为空');
                return;
            }

            $.ajax({
                type: 'post',
                dataType: 'json',
                url: /*[[@{/file/rename}]]*/'',
                data: {
                    fileId: fileId,
                    newName: newName
                },
                success: function(data) {
                    message(data.msg);
                    if (data.success) {
                        $("#rename-dialog-id").dialog('close');
                        $("#flexigrid-id").flexReload();
                    }
                },
                error: function() {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        // 批量删除文件到回收站
        function batchDeleteToRecycle() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0);
            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/'请选择文件');
                return;
            }

            var fileNames = $("#flexigrid-id").getFlexigridiAttrByIndex(1);
            $("#delete-file-id").val(ids.join(','));
            $("#delete-file-name").text(fileNames.join(','));
            $("#delete-to-recycle-dialog-id").dialog('open');
        }



        // 添加顶部修改文件名按钮的事件绑定
        $("#rename-file-btn").click(function() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0);
            var fileNames = $("#flexigrid-id").getFlexigridiAttrByIndex(1);

            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/'请选择文件');
                return;
            }

            if (ids.length > 1) {
                message(/*[[#{file.rename.multi.select}]]*/'只能选择一个文件进行重命名');
                return;
            }

            renameFile(ids[0], fileNames[0]);
        });
        /**
         * 文件复制
         */
        function copyFile() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#copy-file-btn").attr('ids',ids)
            var parentId = $("#file-folder-id").attr("parent-id");
            $("#copy-file-btn").attr('src-uuid',parentId)

            // 清除剪切状态
            $("#cut-file-btn").removeAttr('ids')
            $("#cut-file-btn").removeAttr('src-uuid')

            $("#paste-file-btn").removeClass('hidden')
            $("#file-paste-mum-id").text(ids.length+"")
        }

        /**
         * 文件剪切
         */
        function cutFile() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#cut-file-btn").attr('ids',ids)
            var parentId = $("#file-folder-id").attr("parent-id");
            $("#cut-file-btn").attr('src-uuid',parentId)

            // 清除复制状态
            $("#copy-file-btn").removeAttr('ids')
            $("#copy-file-btn").removeAttr('src-uuid')

            $("#paste-file-btn").removeClass('hidden')
            $("#file-paste-mum-id").text(ids.length+"")
        }

        /**
         * 文件分享
         * @param fileUuid
         * @param fileName
         */
        function shareFileInfo(fileUuid,fileName) {
            $("#share-file-name").attr("fileUuid",fileUuid);
            $("#share-file-name").text(fileName);
            $("#share-file-dialog-id").dialog('open');

            // 对话框打开后自动生成分享链接
            setTimeout(function() {
                queryShareUrl();
            }, 100);
        }

        /**
         * 查询分享地址
         */
        function queryShareUrl() {
            var fileUuid = $("#share-file-name").attr("fileUuid");
            var fileValidity = $("#share-file-validity").val()

            if (!fileUuid) {
                message('文件ID不能为空');
                return;
            }

            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryShareUrl}]]*/'',
                data: [
                    {name:"fileUuid",value: fileUuid},
                    {name:"fileValidity",value: fileValidity},
                ],
                success: function (data) {
                    console.info(`queryShareUrl:${JSON.stringify(data)}`)

                    // 检查返回的数据结构
                    if (data && data.success) {
                        // 尝试从不同的字段获取分享链接 - 扩展更多可能的字段名
                        var shareUrl = data['code'] || data['url'] || data['link'] || data['shareUrl'] ||
                                      data['shareUrl'] || data['share_url'] || data['shareLink'] ||
                                      data['share_link'] || data['downloadUrl'] || data['download_url'] ||
                                      data['accessUrl'] || data['access_url'];

                        // 如果shareUrl是消息文本，则不是真正的分享链接
                        if (shareUrl && shareUrl !== data['msg'] && !shareUrl.includes('成功') && !shareUrl.includes('失败')) {
                            // 如果找到了分享链接（不是消息文本）
                            $("#share-file-url-id").val(shareUrl);
                        } else {
                            // 如果没有找到分享链接，显示详细的错误信息
                            $("#share-file-url-id").val('分享链接生成失败，请重试');
                            console.error('未找到分享链接字段，返回数据：', data);
                            console.error('尝试的字段名：code, url, link, shareUrl, share_url, shareLink, share_link, downloadUrl, download_url, accessUrl, access_url');
                        }
                    } else {
                        // 操作失败
                        var errorMsg = data && data.msg ? data.msg : '分享链接生成失败';
                        $("#share-file-url-id").val(errorMsg);
                        message(errorMsg);
                    }
                },
                error: function(msg){
                    $("#share-file-url-id").val('网络错误，请重试');
                    message(/*[[#{common.error}]]*/'网络错误');
                }
            });

        }

        function debugShareData() {
            var fileUuid = $("#share-file-name").attr("fileUuid");
            var fileValidity = $("#share-file-validity").val();
            var shareUrl = $("#share-file-url-id").val();

            var debugInfo = `
                <div style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-top: 5px;">
                    <p><strong>文件ID:</strong> ${fileUuid || '未设置'}</p>
                    <p><strong>有效期:</strong> ${fileValidity || '未设置'} 天</p>
                    <p><strong>当前分享链接:</strong> ${shareUrl || '未生成'}</p>
                    <p><strong>提示:</strong> 请检查浏览器控制台的详细日志信息</p>
                </div>
            `;
            $("#debug-info").html(debugInfo);
        }


        /**
         * 粘贴文件
         */
        function pasteFile() {
            var targetDirectoryId = $("#file-folder-id").attr("parent-id");
            var copyIds = $("#copy-file-btn").attr('ids');
            var cutIds = $("#cut-file-btn").attr('ids');
            var operation = '';
            var fileIds = '';

            if (copyIds) {
                operation = 'copy';
                fileIds = copyIds;
            } else if (cutIds) {
                operation = 'cut';
                fileIds = cutIds;
            } else {
                message(/*[[#{file.paste.no.files}]]*/'剪贴板中没有文件');
                return;
            }

            // 检查是否有同名文件冲突
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/checkConflict}]]*/'',
                data: {
                    fileIds: fileIds,
                    targetDirectoryId: targetDirectoryId,
                    operation: operation
                },
                success: function(data) {
                    if (data.success) {
                        if (data.conflicts && data.conflicts.length > 0) {
                            // 有冲突，显示冲突处理对话框
                            showConflictDialog(data.conflicts, fileIds, targetDirectoryId, operation);
                        } else {
                            // 没有冲突，直接执行粘贴
                            executePaste(fileIds, targetDirectoryId, operation, 'skip');
                        }
                    } else {
                        message(data.msg);
                    }
                },
                error: function() {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        /**
         * 显示冲突处理对话框
         */
        function showConflictDialog(conflicts, fileIds, targetDirectoryId, operation) {
            var conflictList = '';
            for (var i = 0; i < conflicts.length; i++) {
                conflictList += '<li>' + conflicts[i] + '</li>';
            }
            $("#conflict-file-list").html(conflictList);
            $("#conflict-dialog-id").attr('fileIds', fileIds);
            $("#conflict-dialog-id").attr('targetDirectoryId', targetDirectoryId);
            $("#conflict-dialog-id").attr('operation', operation);
            $("#conflict-dialog-id").dialog('open');
        }

        /**
         * 执行粘贴操作
         */
        function executePaste(fileIds, targetDirectoryId, operation, conflictAction) {
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/paste}]]*/'',
                data: {
                    fileIds: fileIds,
                    targetDirectoryId: targetDirectoryId,
                    operation: operation,
                    conflictAction: conflictAction
                },
                success: function(data) {
                    message(data.msg);
                    if (data.success) {
                        // 清除剪贴板状态
                        $("#copy-file-btn").removeAttr('ids');
                        $("#copy-file-btn").removeAttr('src-uuid');
                        $("#cut-file-btn").removeAttr('ids');
                        $("#cut-file-btn").removeAttr('src-uuid');
                        $("#paste-file-btn").addClass('hidden');

                        // 刷新文件列表
                        $("#flexigrid-id").flexReload();
                    }
                },
                error: function() {
                    message(/*[[#{common.error}]]*/'操作失败');
                }
            });
        }

        /**
         * 处理冲突 - 覆盖
         */
        function handleConflictOverwrite() {
            var fileIds = $("#conflict-dialog-id").attr('fileIds');
            var targetDirectoryId = $("#conflict-dialog-id").attr('targetDirectoryId');
            var operation = $("#conflict-dialog-id").attr('operation');

            $("#conflict-dialog-id").dialog('close');
            executePaste(fileIds, targetDirectoryId, operation, 'overwrite');
        }

        /**
         * 处理冲突 - 跳过
         */
        function handleConflictSkip() {
            var fileIds = $("#conflict-dialog-id").attr('fileIds');
            var targetDirectoryId = $("#conflict-dialog-id").attr('targetDirectoryId');
            var operation = $("#conflict-dialog-id").attr('operation');

            $("#conflict-dialog-id").dialog('close');
            executePaste(fileIds, targetDirectoryId, operation, 'skip');
        }
    </script>
    <style>
        a.hidden{
            display: none;
        }
        #file-paste-mum-id{
            color: red;
        }
    </style>
</head>
<body>
<header>
    <input id="file-name-id" th:placeholder="#{file.name.plc}" class="form-control" style="width: 200px; display: inline-block;">
    <a href="#" class="btn btn-info" onclick="query()">
        <i class="glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="uploadFile()">
        <i class="glyphicon glyphicon-upload"></i>
        <span th:text="#{file.upload.btn}"></span>
    </a>
    <a href="#" class="btn btn-info" onclick="upDir()"  th:title="#{file.up.folder}">
        <i class="glyphicon glyphicon-open"></i>
    </a>
    <input id="file-folder-id" value="/" parent-id ="-1">
    <a href="#" class="btn btn-info" onclick="syncFileData()">
        <i class="glyphicon glyphicon-refresh"></i>
        <span th:text="#{file.sync.data}">同步文件</span>
    </a>
    <a href="#" class="btn btn-info" id="rename-file-btn">
        <i class="glyphicon glyphicon-edit"></i>
        <span th:text="#{file.rename}">修改文件名</span>
    </a>
    <a href="#" class="btn btn-info" id="download-file-btn">
        <i class="glyphicon glyphicon-download"></i>
        <span th:text="#{file.download}">下载</span>
    </a>
    <a href="#" class="btn btn-info" id="copy-file-btn" onclick="copyFile()">
        <i class="glyphicon glyphicon-copy"></i>
        <span th:text="#{file.copy}">复制</span>
    </a>
    <a href="#" class="btn btn-info" id="cut-file-btn" onclick="cutFile()">
        <i class="glyphicon glyphicon-scissors"></i>
        <span th:text="#{file.cut}">剪切</span>
    </a>
    <a href="#" class="btn btn-info hidden" id="paste-file-btn" onclick="pasteFile()">
        <i class="glyphicon glyphicon-paste"></i>
        <span th:text="#{file.paste}">粘贴</span>
        (<span id="file-paste-mum-id"></span>)
    </a>
</header>

<!-- 表格容器 -->
<table id="flexigrid-id"></table>

<!-- 权限修改对话框 -->
<div id="modify-permission-dialog-id" sec:authorize="hasRole('ROLE_cldk_file_permission')" style="display: none">
    <input type="hidden" id="current-file-id" value="">
    <div class="form-group">
        <span th:text="#{file.shared.users}">共享用户</span>
        <ul id='user-permission-ztree-id' class="ztree"></ul>
    </div>

    <div class="form-group">
        <span th:text="#{file.permission.setting}">权限设置</span>
        <select id="permission-type-select" class="form-control">
            <option value="view">[[#{file.permission.view}]]</option>
            <option value="edit">[[#{file.permission.edit}]]</option>
            <option value="admin">[[#{file.permission.admin}]]</option>
        </select>
    </div>
</div>

<!-- 重命名对话框 -->
<div id="rename-dialog-id" style="display: none"> <!-- 移除权限控制属性 -->
    <p>[[#{file.rename.confirm}]]</p>
    <input type="text" id="new-file-name" class="form-control" value="">
    <input type="hidden" id="rename-file-id" value="">
</div>

<!-- 删除到回收站确认对话框 -->
<div id="delete-to-recycle-dialog-id" sec:authorize="hasRole('ROLE_cldk_file_del')" style="display: none">
    <p>[[#{file.delete.confirm}]]</p>
    <span id="delete-file-name"></span>
    <input type="hidden" id="delete-file-id" value="">
</div>

<!-- 上传对话框 -->
<div id="upload-file-dialog-id" style="display: none;">
    <form id="upload-file-form-id" enctype="multipart/form-data" method="post" th:action="@{/file/uploadFile}">
        <input name="parentId" id="upload-file-parent-id" type="hidden">
        <div class="form-group">
            <span th:text="#{file.name}"></span>
            <input name="fileName" id="upload-file-name-id" pattern="^.+$" type="file">
        </div>
    </form>
</div>

<!-- 上传成功提示对话框 -->
<div id="upload-success-dialog" style="display: none;">
    <p id="upload-success-message"></p>
    <div id="uploaded-files-list" style="margin-top: 10px; max-height: 200px; overflow-y: auto;"></div>
</div>

<!-- 注释掉分享文件对话框 -->
<!--
<div id="share-file-dialog-id" style="display: none;">
    <div class="form-group">
        <span th:text="#{share.validity.period}">有效期</span>
        <select id="share-validity-period" class="form-control">
            <option value="1d" th:text="#{share.validity.1day}">1天</option>
            <option value="3d" th:text="#{share.validity.3days}">3天</option>
            <option value="1w" th:text="#{share.validity.1week}">1周</option>
            <option value="2w" th:text="#{share.validity.2weeks}">2周</option>
            <option value="1m" th:text="#{share.validity.1month}">1月</option>
            <option value="6m" th:text="#{share.validity.6months}">6月</option>
            <option value="1y" th:text="#{share.validity.1year}">1年</option>
            <option value="custom" th:text="#{share.validity.custom}">自定义</option>
        </select>
    </div>
    <div class="form-group" id="custom-time-group" style="display: none;">
        <span th:text="#{share.validity.custom.time}">自定义时间</span>
        <input type="datetime-local" id="share-custom-time" class="form-control">
    </div>
    注释掉被分享人员选择功能
    <div class="form-group">
        <span th:text="#{share.shared.users}">被分享人员</span>
        <ul id="share-user-ztree-id" class="ztree"></ul>
    </div>
    -->
</div>

<!-- 文件冲突处理对话框 -->
<div id="conflict-dialog-id" style="display: none;">
    <p>目标位置已存在以下同名文件，请选择处理方式：</p>
    <ul id="conflict-file-list" style="margin: 10px 0; padding-left: 20px;">
    </ul>
    <div style="margin-top: 15px;">
        <button type="button" class="btn btn-warning" onclick="handleConflictOverwrite()">
            <i class="glyphicon glyphicon-ok"></i> 覆盖全部
        </button>
        <button type="button" class="btn btn-default" onclick="handleConflictSkip()">
            <i class="glyphicon glyphicon-remove"></i> 跳过全部
        </button>
    </div>
</div>

<!--&lt;!&ndash; 引入脚本 &ndash;&gt;-->
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<!--<script th:src="@{/assets/js/flexigrid.js}"></script>-->
<!--<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>-->
<div id="share-file-dialog-id" style="display: none">
    <div class="form-group">
        <label th:text="#{file.name}">文件名</label>
        <div class="form-control" id="share-file-name" style="min-height: 20px; padding: 6px 12px; background-color: #f5f5f5; border: 1px solid #ccc; border-radius: 4px;"></div>
    </div>

    <div class="form-group">
        <label th:text="#{file.share.validity}">有效期(天)</label>
        <input class="form-control" id="share-file-validity" type="number" value="1" onchange="queryShareUrl()">
    </div>

    <div class="form-group">
        <label th:text="#{file.share.url}">分享链接</label>
        <textarea class="form-control" id="share-file-url-id" style="height: 50px"></textarea>
    </div>

<!--    <div class="form-group" style="margin-top: 10px;">-->
<!--        <button type="button" class="btn btn-info btn-sm" onclick="debugShareData()">调试信息</button>-->
<!--        <span id="debug-info" style="margin-left: 10px; color: #666; font-size: 12px;"></span>-->
<!--    </div>-->
</div>
    <!-- 播放器容器 -->
    <div id="media-player" style="display:none; position:fixed; bottom:0; left:0; width:100%; background:#f5f5f5; padding:10px; z-index:1000;">
        <audio id="audio-player" controls style="width:100%; display:none"></audio>
        <video id="video-player" controls style="width:100%; display:none"></video>
        <button onclick="closePlayer()" style="position:absolute; right:10px; top:10px;">关闭</button>
    </div>

    <script>
        // 播放文件
        function playFile(fileId, fileName) {
            const mediaPlayer = document.getElementById('media-player');
            const audioPlayer = document.getElementById('audio-player');
            const videoPlayer = document.getElementById('video-player');
            
            // 华为云播放地址 - 直接使用完整文件名作为路径
            const fileUrl = `https://lixiang111.obs.cn-north-4.myhuaweicloud.com/${fileName}`;
            
            // 根据文件扩展名判断媒体类型
            const ext = fileName.split('.').pop().toLowerCase();
            const isAudio = ['mp3','wav','ogg','aac','flac','m4a'].includes(ext);
            const isVideo = ['mp4','webm','ogg','mov','avi','mkv','flv','wmv'].includes(ext);
            
            if (isAudio) {
                audioPlayer.src = fileUrl;
                audioPlayer.style.display = 'block';
                videoPlayer.style.display = 'none';
                mediaPlayer.style.display = 'block';
                audioPlayer.play().catch(e => {
                    console.error('音频播放失败:', e);
                    alert('音频播放失败，请检查文件权限和格式');
                });
            } else if (isVideo) {
                videoPlayer.src = fileUrl;
                videoPlayer.style.display = 'block';
                audioPlayer.style.display = 'none';
                mediaPlayer.style.display = 'block';
                
                // 添加错误事件监听
                videoPlayer.onerror = function() {
                    console.error('视频播放错误:', videoPlayer.error);
                    alert('视频播放失败，请确保：\n1. 文件已正确上传\n2. 华为云OBS已设置Content-Type\n3. 文件可公开访问');
                };
                
                videoPlayer.play().catch(e => {
                    console.error('视频播放失败:', e);
                    alert('视频播放失败，请检查文件权限和格式');
                });
            } else {
                alert('不支持的文件类型');
            }
        }
        
        // 关闭播放器
        function closePlayer() {
            document.getElementById('media-player').style.display = 'none';
            document.getElementById('audio-player').pause();
            document.getElementById('video-player').pause();
        }
    </script>
</body>
</html>
